/**
 * @ClassName:
 * @author:
 * @Description:
 * @Date
 **/
//链表实现的队列，每次从尾部节点添加元素，从头部节点删除元素
public class LinkedListQueue<E> implements Queue<E> {

    private class Node {
        public E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    private Node head, tail;
    private int size;

    public LinkedListQueue() {
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public void enqueue(E e) {
        Node node = new Node(e);
        //链表尾部插入节点
        if (tail == null) {
            tail = node;
            head = tail;
        } else {
            tail.next = node;
            tail = tail.next;
        }
        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("can not dequeue");
        }
        //被删除的元素
        Node ret = head;
        head = head.next;
        ret.next = null;
        //如果元素全部出队了
        if (head == null) {
            tail = null;
        }
        size--;
        return ret.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("is empty");
        }
        return head.e;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Queue front:");
        Node curr = head;
        while (curr != null) {
            builder.append(curr + "->");
            curr = curr.next;
        }
        builder.append("NULL->" + tail);
        return builder.toString();
    }
}
